// 创建web服务器， 书写后端接口，供promise阶段的文件去访问

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 托管静态文件
app.use(express.static('b - Promise'));
// 处理客户端请求参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置跨域，允许任何请求方式请求我接口的数据
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET,POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-with');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
  next();
});

app.get('/addData', (req, res) => {
  res.send('Hello axios');
});

// AXIOS GET
app.get('/axios/:id', (req, res) => {
  res.send('axios get');
});
// AXIOS DELETE
app.delete('/axios', (req, res) => {
  res.send('axios -  delete: ' + req.query.id);
});
// AXIOS POST
app.post('/axios', (req, res) => {
  res.send('axios - post:' + req.body.uname + '=============' + req.body.pwd);
});
// AXIOS PUT
app.put('/axios/:id', (req, res) => {
  res.send(
    'axios - put:' +
      req.params.id +
      '====' +
      req.body.uname +
      '====' +
      req.body.pwd
  );
});
// AXIOS json 全局配置
app.get('/axios-json', (req, res) => {
  res.json({
    uname: 'ls',
    age: 12,
  });
});

// AXIOS 拦截器
app.get('/addData', (req, res) => {
  res.send('hello axios-拦截器');
});

// async处理对个异步请求 一：
app.get('/async1', (req, res) => {
  res.send('hello - async1');
});
// async处理对个异步请求 二：
app.get('/async2', (req, res) => {
  if (req.query.info == 'hello - async1') {
    res.send('hello - async2');
  } else {
    res.send('服务器未知错误·');
  }
});
// 开启web服务器，监听3000端口，客户端http://localhost:3000/xxx请求web服务器的接口数据
app.listen(3000, () => {
  console.log('服务器已经启动');
});
